<template>
  <div>
    <el-container>
      <el-aside style="width: 400px;background-color: white">
        <el-card
            @mouseenter="flag=true" @mouseleave="flag=false"
            class="main-material"
            :class="{'bgc':flag}"
            body-style="margin-top:15px;padding: 0px; position: relative; min-height: 350px;">
          <img
              v-show="dialogImageUrl!==''"
              :src="dialogImageUrl"
              height="250"
              style="width: 100%"
          />
          <el-image v-show="dialogImageUrl===''"
                    style="width: 100%;height: 250px">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture/>
                </el-icon>
              </div>
            </template>
          </el-image>
          <div class="main-material-title">
            {{ title }}
          </div>
          <div class="main-material-desc">{{ contentsummary }}</div>
          <div class="material-edit-pan" v-show="flag">
            <div title="编辑" class="edit-pan-left">
            </div>
          </div>

        </el-card>
      </el-aside>
      <el-main>
        <div class="edit-tips">正在编辑主图文</div>
        <div class="edit-content-title">标题</div>
        <div>
          <el-input v-model="title" maxlength="36" show-word-limit
                    size="large" placeholder="请输入内容,最多36个字符" clearable></el-input>
        </div>
        <div class="edit-content-summary">摘要</div>
        <div>
          <el-input v-model="contentsummary" maxlength="100" show-word-limit
                    size="large" placeholder="请输入内容,最多100个字符" clearable></el-input>
        </div>
        <div class="edit-content-majorpic">封面（首图封面建议尺寸：720*400）</div>
        <el-checkbox v-model="checked1" label="在正文顶部显示封面图片" size="large"/>

        <ImageUpload :limit="1" @update:modelValue="receiveUrl" :fileUrl="dialogImageUrl"/>

        <div class="view-content-type m-t-20" v-show="showContent">
          <div class="view-content-type-title">请选择用户点击图文消息后查看的内容</div>
          <div class="flex-row">
            <div class="flex-column cursor-point eidt-text" @click="toggleMainContext">
              <img
                  src=""
                  width="120" height="120">
              <span class="m-t-10">编辑正文</span>
            </div>
            <div class="flex-column cursor-point goto-net" @click="toggleShowOther"><img
                src=""
                width="120" height="120"> <span
                class="m-t-10">跳转至网页</span></div>
          </div>
        </div>
        <div class="content-type" v-show="showContextType">
          <div class="content-type-edit-check">
            <el-button @click="toggleShowMain">请选择</el-button>
            <el-button @click="toggleShowOther">跳转至网页</el-button>
          </div>
          <div class="quill-editor">
            <div style="border: 1px solid #ccc">
              <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
              />
              <Editor
                  style="height: 500px; overflow-y: hidden;"
                  v-model="valueHtml"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
              />
            </div>
          </div>
          <div class="edit-content-original-link">添加原文链接</div>
          <el-input v-model="originalLink" maxlength="100" show-word-limit
                    size="large" placeholder="请输入内容,最多100个字符" clearable></el-input>
        </div>
        <div v-show="showNetConfig">
          <div style="display: flex; justify-content: space-between;margin-top: 20px;
             align-items: center;
              ">
            <div class="content-type-edit-check">添加跳转至网页链接</div>
            <el-button @click="toggleMainContext">编辑正文</el-button>
          </div>

          <el-input style="margin-top: 20px;" v-model="netconfig" maxlength="100" show-word-limit
                    size="large" placeholder="请输入内容,最多100个字符" clearable>

          </el-input>
        </div>
        <el-button style="margin-top: 10px;width: 100px;" type="primary" size="large" @click="save">保存</el-button>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup name="tuwen">
import {addImagetext,getImagetext,updateImagetext} from '/@/api/publicaccount/imagetext'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {ArrowRight, Picture as IconPicture} from '@element-plus/icons-vue'
import {onBeforeUnmount, shallowRef, onMounted} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import { IEditorConfig } from '@wangeditor/editor'

import usePublicAccount from '/@/stores/modules/publicaccount'
import {ref} from "vue";
import {parseTime} from '/@/utils/timeutils'
import {useRoute, useRouter} from "vue-router";
import { Session } from '/@/utils/storage';
import {commonUpload} from  '/@/utils/commonUpload.js'


const test = ArrowRight;
const test2 = IconPicture;
const publicAccount = usePublicAccount();
const name = publicAccount.selectAccount;
const username = publicAccount.selectid;
const flag = ref(false)
const title = ref("");
const contentsummary = ref("");
const checked1 = ref(true);

const fileList = ref<UploadUserFile[]>([])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const originalLink = ref("");
const showContextType = ref(false);

const handleRemove: (uploadFile, uploadFiles) => void = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  dialogImageUrl.value = '';
}

const handleSuccess: (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) => void = (response, uploadFile, uploadFiles) => {
  console.info("uploadFile", uploadFile, "uploadFiles:", uploadFiles);
  dialogImageUrl.value = uploadFile.url;
}

const handlePictureCardPreview: (uploadFile) => void = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const showContent = ref(true);

const editorRef = shallowRef()
const valueHtml = ref('')

const toolbarConfig = {}


const baseUrl = import.meta.env.VITE_API_BASE_URL;
const uploadApi = ref(import.meta.env.VITE_API_BASE_URL + "/common/upload");
const headers = ref({Authorization: "Bearer " + Session.getToken()});

const editorConfig: Partial<IEditorConfig> = {  // TS 语法
// const editorConfig = {                       // JS 语法
  MENU_CONF: {},
  placeholder: '请输入'
  // 其他属性...
}
editorConfig.MENU_CONF['codeSelectLang'] = {
  // 代码语言
  codeLangs: [
    { text: 'CSS', value: 'css' },
    { text: 'HTML', value: 'html' },
    { text: 'XML', value: 'xml' },
    // 其他
  ]
}

editorConfig.MENU_CONF['uploadImage'] = {
  server: uploadApi.value,
  fieldName: 'file',
  async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
    // async customUpload(file, insertFn) {                   // JS 语法
    // file 即选中的文件
    // 自己实现上传，并得到图片 url alt href
    // 最后插入图片
    let result=  await commonUpload(file);
    console.info("result",result);
    insertFn(result.data.url,result.data.originalFilename,result.data.url);
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const mode = ref('default');

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const toggleShowMain = () => {
  showContent.value = true;
  showContextType.value = false;
}

const toggleMainContext = () => {
  showContent.value = false;
  showContextType.value = true;
  showNetConfig.value = false;
}

const showNetConfig = ref(false);
const netconfig = ref("");

const toggleShowOther = () => {
  showContent.value = false;
  showContextType.value = false;
  showNetConfig.value = true;
}

const receiveUrl = (url) => {
  dialogImageUrl.value = url;
}

const updated = ref(false);
const route = useRoute();
const router =useRouter();
onMounted( async ()=>{
    const id = route.query.id;
    if(id) {
        updated.value=true;
        const imageTextResult = await getImagetext(id);
        console.info("imageTextResult:", imageTextResult);
        const queryObj = imageTextResult.data;
        if (queryObj) {
          title.value = queryObj.title
          contentsummary.value = queryObj.summary;
          if (queryObj.body) {
            showContent.value = false;
            showContextType.value = true;
            showNetConfig.value = false;
            valueHtml.value = decodeURIComponent(queryObj.body)
          }
          originalLink.value = queryObj.originalUrl;
          dialogImageUrl.value= queryObj.materialKey;
        }
    }
})

const save = () => {
  const data = {
    pid: Date.now(),
    pusername: username,
    materialKey: dialogImageUrl.value,
    title: title.value,
    summary: contentsummary.value,
    creationTime: parseTime(new Date()),
    suborder: 0,
    "body": encodeURIComponent(''+valueHtml.value),
    originalUrl: originalLink.value,
    shareable: 0,
    isShowCover: checked1.value ? 0 : 1,
    status: 1
  }
  console.info("data", data);
  if(updated.value){
      data.id = route.query.id;
      updateImagetext(data).then(resp =>{
        console.info("resp", resp)
        router.push('/publicAccountManager/index?name=' + name + '&username=' + username);
      });
  }else {
    addImagetext(data).then((resp) => {
      console.info("resp", resp)
      router.push('/publicAccountManager/index?name=' + name + '&username=' + username);
    });
  }
}


</script>

<style scoped lang="scss">

.bgc {
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 10;
}

.content-type {
  position: relative;
  text-align: left;

  .quill-editor {
    margin-top: 20px;
    min-height: 500px;
  }

  .content-type-edit-check {
    text-align: right;
    position: relative;
    right: 20px;
    top: 10px;
    font-size: 14px;
    color: #4e7cfd;
  }

  .edit-content-original-link {
    text-align: left;
    font-size: 14px;
    color: #4e7cfd;
    line-height: 40px;
  }

  .content-select {
    text-align: right;
    position: relative;
    right: 40px;
    top: 10px;
    font-size: 14px;
    color: #4e7cfd;
  }

  .content-type-edit-check {
    text-align: right;
    position: relative;
    right: 20px;
    top: 10px;
    font-size: 14px;
    color: #4e7cfd;
  }
}

.view-content-type {
  padding-bottom: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;

  .flex-row {
    display: flex;
    -webkit-box-direction: normal;

    .cursor-point {
      cursor: pointer;
    }

    .flex-column {
      display: flex;
      flex-direction: column;
    }

    .eidt-text {
      margin: 10px 40px;
      text-align: center;
    }

    .m-t-10 {
      margin-top: 10px;
    }

    .goto-net {
      margin: 10px 40px;
      text-align: center;
    }
  }

  .view-content-type-title {
    padding-left: 20px;
    padding-top: 10px;
    text-align: left;
    font-size: 14px;
    color: #333;
    line-height: 40px;
  }
}

.m-t-20 {
  margin-top: 20px;
}

.box-card {
  width: 100%;
  height: 40px;
}

.edit-tips {
  font-size: 20px;
  text-align: left;
}

.edit-content-summary, .edit-content-majorpic, .edit-content-title {
  text-align: left;
  font-size: 14px;
  color: #333;
  line-height: 40px;
}

:deep(.hide .el-upload--picture-card) {
  display: none;
}

.main-material {
  min-height: 250px;
  background-image: url();
  background-repeat: no-repeat;
  background-position: 50%;

  .main-material-title {
    position: absolute;
    top: 230px;
    color: white;
    background-color: gray;
    width: 310px;
    white-space: nowrap;
  }

  .material-edit-pan {
    display: flex;
    align-items: center;
    align-content: center;
    position: absolute;
    margin-top: 16px;
    cursor: pointer;
    top: 0;
    width: 312px;
    height: 312px;

    /*z-index: 1;*/
    /*background-color: rgba(0,0,0,.4);*/

    .edit-pan-left {
      margin: auto;
      display: inline-block;
      width: 36px;
      line-height: 36px;
      height: 36px;
      background-color: #fff;
      border-radius: 18px;
      background-size: 50%;
      background-repeat: no-repeat;
      background-position: 50%;
      background-image: url();
    }
  }
}


</style>
